#ifndef OSGCLASS_H
#define OSGCLASS_H


#include "common.h"

class simpleCallBack:public osg::NodeCallback
{
public:
    simpleCallBack():_angle(0)
    {

    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        //创建矩阵转换节点
        osg::ref_ptr<osg::MatrixTransform> mt = dynamic_cast<osg::MatrixTransform*>(node);
        //创建矩阵
        osg::Matrix mx;
        //绕着Z轴旋转
        mx.makeRotate(_angle,osg::Vec3(0.0,0.0,1.0));

        //设置矩阵
        mt->setMatrix(mx);

        _angle+=0.01;

        //继续遍历
        traverse(node,nv);

    }

public:
    //旋转角度
    double _angle;
};
class lineCallBack:public osg::NodeCallback
{
public:
    lineCallBack():n(0)
    {

    }
    void setMarry(osg::ref_ptr<osg::FloatArray> ma)
    {
        mA = ma;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        //创建矩阵转换节点
        osg::ref_ptr<osg::MatrixTransform> mt = dynamic_cast<osg::MatrixTransform*>(node);
        //创建矩阵
        osg::Matrix mx;
        if(n == 99)
            n = 0;
        n++;
        //移动
        mx.makeRotate(mA->at(n),osg::Vec3(0.0,0.0,1.0));
        //设置矩阵
        mt->setMatrix(mx);

        //继续遍历
        traverse(node,nv);

    }

public:
    //移动位置
    osg::ref_ptr<osg::FloatArray> mA;
    int n;
};
class osgWidget : public QWidget, public osgViewer::CompositeViewer
{
public:
    osgWidget(/*osg::ref_ptr<osg::Vec3Array> vertex,
              osg::ref_ptr<osg::DrawElementsUInt> indice,
              osg::ref_ptr<osg::Vec4Array> color*/): QWidget()
    {
        initViewerCamera();
        //setData(vertex,indice,color);
        setViewerData();
        setViewerLayout();
        setTimer();
    }
    virtual void paintEvent( QPaintEvent* event )
    { frame(); }

    void setData(osg::ref_ptr<osg::Vec3Array> vertex,
                 osg::ref_ptr<osg::DrawElementsUInt> indice,
                 osg::ref_ptr<osg::Vec4Array> color)
    {
        osg::ref_ptr<osg::Geode> geode = new osg::Geode();
        osg::ref_ptr<osg::Geometry> geo = new osg::Geometry;
        geo->setVertexArray(vertex);

        geo->addPrimitiveSet(indice);

        geo->setColorArray(color);
        geo->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
        osg::ref_ptr<osg::Vec3Array> norm = new osg::Vec3Array;
        norm->push_back(osg::Vec3(0.f, -1.f, 0.f));
        geo->setNormalArray(norm, osg::Array::BIND_OVERALL);
        geo->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);

        geode->addDrawable(geo);

    }

protected:
    void initViewerCamera()
    {
        setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
        // disable the default setting of viewer.done() by pressing Escape.
        setKeyEventSetsDone(0);
        osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->windowName = "";
        traits->windowDecoration = false;
        traits->x = 0;
        traits->y = 0;
        traits->width = 800;
        traits->height = 600;
        traits->doubleBuffer = true;
        traits->alpha = ds->getMinimumNumAlphaBits();
        traits->stencil = ds->getMinimumNumStencilBits();
        traits->sampleBuffers = ds->getMultiSamples();
        traits->samples = ds->getNumMultiSamples();
        gw = new osgQt::GraphicsWindowQt(traits.get());
        view = new osgViewer::View;
        addView( view );

        osg::Camera* camera = view->getCamera();
        camera->setGraphicsContext(gw);

        camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
        camera->setProjectionMatrixAsPerspective(
            30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );
    }
    void setViewerLayout()
    {
        QGridLayout* grid = new QGridLayout;
        grid->addWidget( gw->getGLWidget(), 0, 0 );
        setLayout( grid );
    }
    void setTimer()
    {
        connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
        _timer.start( 10 );
    }
    virtual void setViewerData()//后面就在这里添加代码控制绘图
    {

 /*       osg::ref_ptr<osg::Group> root = new osg::Group;
        osg::ref_ptr<osg::Geode> geode = new osg::Geode;

        osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
        vertices->push_back( osg::Vec3(0.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) );
        osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array;
        normals->push_back( osg::Vec3(0.0f,-1.0f, 0.0f) );
        osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array;
        colors->push_back( osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f) );
        osg::ref_ptr<osg::Geometry> line = new osg::Geometry;
        line->setVertexArray( vertices.get() );
        line->setNormalArray( normals.get() );
        line->setNormalBinding( osg::Geometry::BIND_OVERALL );
        line->setColorArray( colors.get() );
        line->setColorBinding( osg::Geometry::BIND_OVERALL );
        line->addPrimitiveSet( new osg::DrawArrays(GL_LINES, 0, 2) );
        geode->addDrawable(line);


        root->addChild(geode);
        view->setSceneData(root);
*/
        view->setSceneData(setCallbackLine());

        //view->setSceneData(setPathAnimation());
        //按下w显示网格
        view->addEventHandler( new osgGA::StateSetManipulator(
                                   view->getCamera()->getOrCreateStateSet()) );

        view->setCameraManipulator(new osgGA::TrackballManipulator);
    }
    osg::ref_ptr<osg::Group> setPathAnimation()
    {//路径动画
        //osg图形根节点
        osg::ref_ptr<osg::Group> pathAniRoot = new osg::Group;
        //几何组节点
        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
        geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(0,0,0),0.5)));

        osg::ref_ptr<osg::MatrixTransform> trans = new osg::MatrixTransform();
        trans->setName("AnimatedNode");
        trans->setDataVariance(osg::Object::DYNAMIC);
        osgAnimation::UpdateMatrixTransform* updatecb = new osgAnimation::UpdateMatrixTransform("AnimatedCallback");
        updatecb->getStackedTransforms().push_back(new osgAnimation::StackedTranslateElement("position"));

        trans->setUpdateCallback(updatecb);
        trans->setMatrix(osg::Matrix::identity());
        trans->addChild (geode.get());
        pathAniRoot->addChild(trans);
        pathAniRoot->addChild(geode);

        osg::ref_ptr<osg::Group> grp = new osg::Group;
        osgAnimation::BasicAnimationManager* mng = new osgAnimation::BasicAnimationManager();
        grp->setUpdateCallback(mng);
        grp->addChild(pathAniRoot);

        osgAnimation::Vec3LinearChannel* channelAnimation1 = new osgAnimation::Vec3LinearChannel;
        channelAnimation1->setTargetName("AnimatedCallback");
        channelAnimation1->setName("position");
        channelAnimation1->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::Vec3Keyframe(0, osg::Vec3(0,0,0)));
        channelAnimation1->getOrCreateSampler()->getOrCreateKeyframeContainer()->push_back(osgAnimation::Vec3Keyframe(2, osg::Vec3(1,1,0)));
        osgAnimation::Animation* anim1 = new osgAnimation::Animation;
        anim1->addChannel(channelAnimation1);
        anim1->setPlayMode(osgAnimation::Animation::PPONG);
        // We register all animation inside the scheduler
        mng->registerAnimation(anim1);
        //start the animation
        mng->playAnimation(anim1);
        return grp;
    }
    osg::ref_ptr<osg::Geometry> createQuad()
    {
        osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
        vertices->push_back( osg::Vec3(0.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(1.0f, 0.0f, 1.0f) );
        vertices->push_back( osg::Vec3(0.0f, 0.0f, 1.0f) );
        osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array;
        normals->push_back( osg::Vec3(0.0f,-1.0f, 0.0f) );
        osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array;
        colors->push_back( osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f) );
        colors->push_back( osg::Vec4(0.0f, 1.0f, 0.0f, 1.0f) );
        colors->push_back( osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f) );
        colors->push_back( osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f) );
        osg::ref_ptr<osg::Geometry> quad = new osg::Geometry;
        quad->setVertexArray( vertices.get() );
        quad->setNormalArray( normals.get() );
        quad->setNormalBinding( osg::Geometry::BIND_OVERALL );
        quad->setColorArray( colors.get() );
        quad->setColorBinding( osg::Geometry::BIND_PER_VERTEX );
        quad->addPrimitiveSet( new osg::DrawArrays(GL_QUADS, 0, 4) );
        return quad.release();
    }
    osg::ref_ptr<osg::Group> setCallbackAnimation()
    {//回调动画
        osg::ref_ptr<osg::Group> root = new osg::Group;
        //读取模型
        osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("D:\\OpenSceneGraph-Data\\cow.osgt");

        //创建矩阵变换节点
        osg::ref_ptr<osg::MatrixTransform> mt = new osg::MatrixTransform;
        mt->addChild(node.get());

        //设置更新回调函数
        mt->setUpdateCallback(new simpleCallBack());

        root->addChild(mt.get());
        return root;
    }
    osg::ref_ptr<osg::Group> setCallbackLine()
    {
        osg::ref_ptr<osg::Group> root = new osg::Group;
        osg::ref_ptr<osg::Geode> geode = new osg::Geode;

        osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
        vertices->push_back( osg::Vec3(0.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(0.8f, 0.0f, 0.2f) );
        vertices->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) );
        vertices->push_back( osg::Vec3(0.8f, 0.0f, -0.2f) );
        osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array;
        normals->push_back( osg::Vec3(0.0f,-1.0f, 0.0f) );
        osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array;
        colors->push_back( osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f) );
        osg::ref_ptr<osg::Geometry> line = new osg::Geometry;
        line->setVertexArray( vertices.get() );
        line->setNormalArray( normals.get() );
        line->setNormalBinding( osg::Geometry::BIND_OVERALL );
        line->setColorArray( colors.get() );
        line->setColorBinding( osg::Geometry::BIND_OVERALL );
        line->addPrimitiveSet( new osg::DrawArrays(GL_LINES, 0, 6) );
        geode->addDrawable(line);

        osg::ref_ptr<osg::FloatArray> mArry = new osg::FloatArray;

        for(int i=0;i<100;i++)
        {
            mArry->push_back((float)i*0.01f);
        }

        //创建矩阵变换节点
        osg::ref_ptr<osg::MatrixTransform> mt = new osg::MatrixTransform;
        mt->addChild(geode.get());

        //设置更新回调函数
        lineCallBack* cb = new lineCallBack();
        cb->setMarry(mArry);
        mt->setUpdateCallback(cb);

        root->addChild(mt.get());
        return root;
    }

protected:
    QTimer _timer;
    osgQt::GraphicsWindowQt* gw;
    osgViewer::View* view;
};




#endif // OSGCLASS_H
